package z.explorer.ui.common;

import javax.swing.*;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import z.explorer.Main;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ZProgressDialog extends JDialog {

	private static Log log = LogFactory.getLog(ZProgressDialog.class);

	private final static int width = 300;
	private final static int height = 70;

	Handler handler = null;

	private JProgressBar progressBar = new JProgressBar();
	private JLabel messageLabel = new JLabel();

	public ZProgressDialog(JFrame parent, Handler h) {
		super(parent, true);
		handler = h;
		messageLabel.setText(h.getMessage());
		setLocationRelativeTo(parent);
		initUI();
	}

	public ZProgressDialog(Handler h) {
		this(null, h);
	}

	public void initUI() {
		setSize(width, height);
		JPanel panel = new JPanel();
		panel.setLayout(new BorderLayout());
		panel.add(messageLabel, BorderLayout.NORTH);
		panel.add(progressBar, BorderLayout.SOUTH);
		panel.setBorder(BorderFactory.createEtchedBorder());

		messageLabel.setHorizontalAlignment(SwingConstants.CENTER);
		progressBar.setIndeterminate(true);
		progressBar.setOpaque(false);
		progressBar.setForeground(Color.GREEN);
		Container con = getContentPane();
		con.setLayout(new BorderLayout());
		con.add(panel, BorderLayout.CENTER);
	}

	public void run() {
		Thread t = new Thread() {
			public void run() {
				try {
					handler.handle();
				} catch (Exception ex) {
					// for test debug
					ex.printStackTrace();
					log.error(ex.toString());

				} finally {
					dispose();
				}

			}
		};
		t.start();
		setVisible(true);
	}

	/* test */
	public static void main(String args[]) throws InterruptedException {
		Handler h = new Handler() {

			@Override
			public void handle() {
				for (int i = 0; i < 5; i++) {
					try {
						Thread.currentThread().sleep(1000);
						System.out.println("sleep 1 second");
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}

			}

			@Override
			public String getMessage() {
				// TODO Auto-generated method stub
				return "testing ...";
			}

		};

		ZProgressDialog zpd = new ZProgressDialog(null, h);
		zpd.run();
	}
}
